<?php

namespace app\api\model;

use think\Db;
use think\Model;
use think\Validate;

/**
 *
 */
class OrderCreate extends Model
{


    public function ordercreate($data)
    {

        $address_id = $data['address_id'];

        $address = UserAddress::get($address_id);
        if (empty($address)){
            throw new \Exception('请选择地址');
        }
        $auction_id = $data['auction_id'];
        $auction_info = Auction::get($auction_id);
        if ($auction_info['status']!=1){
            throw new \Exception('拍卖品不是进行中状态,无法提交');
        }
        $order_no = $this->order_no();

        if (empty($data['realname'])){
            throw new \Exception('请输入实名姓名');
        }

        if (empty($data['phone'])){
            throw new \Exception('请输入实名手机号');
        }
        if (!Validate::regex($data['phone'], "^1\d{10}$")) {
            throw new \Exception('手机号格式错误');
        }
        if (empty($data['id_card_num'])){
            throw new \Exception('请输入实名身份证号');
        }
        if (!isValidIdCard($data['id_card_num'])){
            throw new \Exception('身份证号格式错误');
        }


        Db::startTrans();

        $order_model = new AuctionOrder();

        try {
            $data_order = [
                'order_no'=>$order_no,
                'user_id'=>$data['user_id'],
                'auction_id'=>$auction_id,
                'auction_name'=>$auction_info['name'],
                'auction_image'=>$auction_info['image'],
                'price'=>$auction_info['deposit'],
                'realname'=>$data['realname'],
                'id_card_num'=>$data['id_card_num'],
                'phone'=>$data['phone'],
                'name'=>$address['name'],
                'mobile'=>$address['mobile'],
                'address'=>$address['full_address'].$address['address'],
                'order_status_name'=>'待交保'
            ];

            $order_model->save($data_order);

            Db::commit();

            return $order_model->order_no;
        } catch (\Exception $e) {
            Db::rollback();
            throw new \Exception($e->getMessage());
        }

    }

    public function order_no(){
        $order_no = null;
        while (true) {
            $order_no = date('YmdHis') . mt_rand(1000, 9999);
            $exist_order_no = AuctionOrder::get(['order_no' => $order_no]);
            if (!$exist_order_no) {
                break;
            }
        }
        return $order_no;
    }

}